<template>
  <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      :ellipsis="false"
      @select="handleSelect"
      :router="true"
      @click="doMenuClick"
  >
    <el-menu-item index="/">
      <img
          style="width: 100px"
          src="../assets/element-plus-logo.svg"
          alt="Element logo"
      />
      <div class="title">电子商务专业课程问答系统</div>
    </el-menu-item>
    <el-menu-item 
    v-if=" role === '管理员'"
    index="/user">用户管理</el-menu-item>
    <el-menu-item
    v-if="role === '教师' || role === '管理员'"
     index="/know">知识库</el-menu-item>
    <div>
      <el-sub-menu index="3" v-if="isLoggedIn">
        <template>{{username}}</template>
        <el-menu-item index="/changeuser">修改个人信息</el-menu-item>
        <!-- <el-menu-item index="xxperson">注销个人信息</el-menu-item> -->
        <el-menu-item index="longinout">退出登录</el-menu-item>
      </el-sub-menu>
      <el-button type="primary" @click="loginIng" v-if="!isLoggedIn">登录</el-button></div>
  </el-menu>
</template>

<script setup>
import { ref, onMounted,computed,watch} from 'vue';
import {useStore} from "vuex";
import {useRouter} from "vue-router";

const store = useStore();
const router = useRouter();
const username = 'libai';
const activeIndex = ref('1')

const isLoggedIn = computed(() => store.state.isLoggedIn);

const role = localStorage.getItem("role");
store.dispatch('checkLogin');

//监听路由变化
watch(
  () =>router.currentRoute.value,
  () =>{
    store.dispatch('checkLogin');
  },
  {immediate:true}
)

const handleSelect = (key, keyPath) => {
  console.log("key:",key)
  console.log("keyPath:",keyPath)
  console.log(key, keyPath);
  if (key == 'longinout'){
    console.log("退出登录了")
    router.push('login')
    //退出登录
    isLoggedIn.value = false;
    localStorage.removeItem('token');
  }
};

const doMenuClick = (key, keyPath) => {
  console.log(key, keyPath);
  if (key == 'changeuser'){
    router.push(
    )
    //修改个人信息
    console.log('修改个人信息');
  }
  if (key == 'xxxperson'){
    //注销个人信息
    console.log('注销个人信息');
  }
  if (key == 'longinout'){
    //退出登录
    console.log('退出登录');
  }
};

const loginIng = () =>{
  router.push("/login")
  
}
 </script>

<style scoped>
.el-menu--horizontal > .el-menu-item:nth-child(1) {
  margin-right: auto;
}
.title{
  color: #007bff;
}
</style>